package com.gamecat.android_tools.Camera2

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.hardware.camera2.params.SessionConfiguration
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.gamecat.android_tools.R
import java.util.*


class Camera2Activity : AppCompatActivity() {
    public final var TAG = "Camera2Activity";
    private var mTextureView: TextureView? = null
    private var mCameraCaptureSession: CameraCaptureSession? = null
    private var mCameraDevice: CameraDevice? = null
    private var mPreviewSurface: Surface? = null


    var qian: CameraCharacteristics? = null
    var hou: CameraCharacteristics? = null
    var qianId: String = ""
    var houId: String = ""


    //private String mCameraId;
    //private Handler mHandler;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera2)

        val manager: CameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
        if (ActivityCompat.checkSelfPermission(
                baseContext,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        val cameraIdList = manager.cameraIdList
        Log.d(
            TAG, "cameraCharacteristics: " + cameraIdList.toString() +
                    "cameraIdList  size " + cameraIdList.size
        )

        cameraIdList.forEach { cameraId ->
            val cameraCharacteristics = manager.getCameraCharacteristics(cameraId)
//            cameraCharacteristics.
//            if (cameraCharacteristics.isHardwareLevelSupported(REQUIRED_SUPPORTED_HARDWARE_LEVEL)) {
            if (cameraCharacteristics[CameraCharacteristics.LENS_FACING] == CameraCharacteristics.LENS_FACING_FRONT) {
                qian = cameraCharacteristics
                qianId = cameraId
                Log.d(TAG, "cameraCharacteristics: qian")
            } else if (cameraCharacteristics[CameraCharacteristics.LENS_FACING] == CameraCharacteristics.LENS_FACING_BACK) {
                Log.d(TAG, "cameraCharacteristics: hou")
                hou = cameraCharacteristics
                houId = cameraId
            }
//            }
        }
        // 默认开启后置摄像头的
        manager.openCamera(houId, object : CameraDevice.StateCallback() {
            override fun onOpened(camera: CameraDevice) {
                mCameraDevice = camera
                mCameraDevice?.apply {
                    createCaptureSession(
                        Arrays.asList(mPreviewSurface),
                        object : CameraCaptureSession.StateCallback() {
                            override fun onConfigured(arg0: CameraCaptureSession) {
                                mCameraCaptureSession = arg0
                                val builder: CaptureRequest.Builder
                                builder =
                                    mCameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
                                builder.addTarget(mPreviewSurface!!)
                                mCameraCaptureSession!!.setRepeatingRequest(
                                    builder.build(),
                                    null,
                                    null
                                )

                            }

                            override fun onConfigureFailed(arg0: CameraCaptureSession) {
                            }
                        },
                        null
                    )
                }


            }

            override fun onDisconnected(camera: CameraDevice) {
                TODO("Not yet implemented")
            }

            override fun onError(camera: CameraDevice, error: Int) {
                camera.close()
            }

        }, null)

        //预览用的surface
        mTextureView = findViewById<TextureView>(R.id.textureView1)
        mTextureView?.apply {
            surfaceTextureListener = object : SurfaceTextureListener {
                override fun onSurfaceTextureAvailable(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
                ) {
                    mPreviewSurface = Surface(surface)
                }

                override fun onSurfaceTextureSizeChanged(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
                ) {
                }

                override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                    return true
                }

                override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
                }

            }
        }

    }
}